package com.boilermaker.demo.service;

import com.boilermaker.demo.enums.BookStatus;
import com.boilermaker.demo.mapper.BookMapper;
import com.boilermaker.demo.model.Book;
import com.boilermaker.demo.model.PageRequest;
import com.boilermaker.demo.model.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookMapper bookMapper;

    public PageResponse<Book> getListByPage(PageRequest pageRequest) {
        Integer count = bookMapper.countAvailableBook();
        List<Book> bookList = bookMapper.selectBookListByPage(pageRequest);
        for (Book book : bookList) {
            book.setStatusCN(BookStatus.getNameByCode(book.getStatus()));
        }
        return new PageResponse<>(count, bookList, pageRequest);
    }

    public boolean checkAndInsertBook(Book book) {
        if (!StringUtils.hasLength(book.getBookName()) ||
                !StringUtils.hasLength(book.getAuthor()) ||
                !StringUtils.hasLength(book.getPublish()) ||
                book.getCount() == null ||
                book.getPrice() == null ||
                book.getStatus() == null) {
            return false;
        }
        bookMapper.insertBook(book);
        return true;
    }

    public boolean updateBook(Book book) {
        Integer i = bookMapper.updateBook(book);
        return i == 1;
    }

    public Book selectBookById(Integer id) {
        return bookMapper.selectBookById(id);
    }

    public boolean deleteBooks(List<Integer> ids) {
        Integer i = bookMapper.deleteBooks(ids);
        return i == ids.size();
    }
}
